import { createRouter, createWebHistory } from 'vue-router'
// 声明导入的是type
import type { RouterOptions } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/',
      name: 'root',
      redirect: '/login'
    },
    {
      name: '404',
      path: '/:catchAll(.*)',
      component: () => import(`@/views/error/404.vue`)
    }
  ]
} as RouterOptions)
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  if (to.name === '404' && to.path !== '/404') {
    if (userStore.currentPath !== to.path) {
      try {
        await userStore.afterLoginAction()
        next(to.fullPath)
      } catch (error) {
        next()
      }
    } else {
      // 当前是404,去到其余页面
      next()
      userStore.setCurrentPath('/404')
    }
  } else {
    // 非刷新页面情况
    next()
    userStore.setCurrentPath(to.path)
  }
})

// 如果服务器和本地版本不一致就刷新页面
router.onError((error) => {
  const fetchResourcesErrors = [
    'Failed to fetch dynamically imported module',
    'Importing a module script failed'
  ]
  if (fetchResourcesErrors.some((item) => error?.message && error.message?.includes(item))) {
    window.location.reload()
  }
})

export default router
